package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

/**
 * @author hu
 * @date 2025/3/4
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler
    public Result exceptionHandle(Exception e) {
        log.info("异常信息->", e);
        return Result.error("出异常了，请联系管理员");
    }

    @ExceptionHandler
    public Result DuplicateExceptionHandle(DuplicateKeyException e) {
        log.info("异常信息->", e);
        String message = e.getMessage();
        int index = message.lastIndexOf("Duplicate entry");
        String errMessage = message.substring(index);
        String[] mes = errMessage.split(" ");
        return Result.error(mes[2] + "已存在");
    }

    @ExceptionHandler
    public Result NumberFormatExceptionHandle(NumberFormatException e, MethodArgumentTypeMismatchException e2) {
        log.info("异常信息->{},{}", e, e2);
        return Result.error("请输入0-100之间");
    }


}
